<template>
  <div class="template-wrapper" style="height: 100%">
    <PptHeader title="模板选择"></PptHeader>
    <div class="template-list" style="height: calc(100% - 52px)">
      <div class="template-area">
        <div class="tabs">
          <div
            v-for="(item, index) in tabs"
            :key="item"
            class="item-tab"
            :class="activeTab === index ? 'active' : ''"
            @click="handleChangeTab(index)"
          >
            {{ item }}
          </div>
        </div>
        <div class="content">
          <header
            v-resize="handleDomResize"
            style="display: flex; justify-content: space-between"
          >
            <div class="template-scene">
              <Select
                :list="sceneList"
                v-model="query.scene"
                title="模板场景"
                @click="handleFilter"
              ></Select>
              <Select
                :list="styleList"
                v-model="query.style"
                title="设计风格"
                @click="handleFilter"
              ></Select>
              <Select
                :list="colorList"
                circle
                title="主题颜色"
                v-model="query.tone"
                @click="handleFilter"
              ></Select>
            </div>
            <el-button type="success" @click="next" :disabled="!selectedTemplate?.id">
              下一步&nbsp;
              <el-icon>
                <component is="Right" />
              </el-icon>
            </el-button>
          </header>
          <div class="template-node">
            <div
              class="node-item"
              style="display: flex; gap: 12px; flex-wrap: wrap"
            >
              <div
                class="node-img"
                v-if="dataList.length"
                v-for="item in dataList"
                :key="item.id"
                :style="{
                  width: '320px',
                  height: '188px',
                  padding: '10px',
                  boxShadow: '0 0 10px rgba(0, 0, 0, 0.1)',
                  backgroundColor:
                    selectedTemplate.id === item.id ? selectedColor : '',
                }"
                @click="handleSelectTemplate(item)"
              >
                <ppt-cover :images="JSON.parse(item.cover)"/>
              </div>
              <div style="margin: 0 auto" v-else>
                <el-empty description="暂无模板" />
              </div>
            </div>
            <Pagination
              :total="dataTotal"
              v-model:limit="query.limit"
              v-model:page="query.page"
              @pagination="getTemplateList"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onBeforeMount } from 'vue'
import PptHeader from '../PptHeader.vue'
import { httpGetCategories, httpGetTemplates } from '@/api/ppt'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import Select from './select.vue'
import Pagination from '@/components/pagination/index.vue'
import { colorToRgba, debounce } from '@/utils/tools'
import { useRouter, useRoute } from 'vue-router'
import { Scene } from '@/enum/ppt'
import { ElLoading } from 'element-plus'
import { PPTDataJson, ServerData } from '@/models/ai-ppt'
import { markdownJsonToServer, markdownToJson, pptOutlineKey } from '@/views/ai-pptx/ppt-helpers'
import { httpOutlineToPptContent } from '@/api/ai-ppt'
import PptCover from '@/components/ppt-cover/index.vue'

const tabs = ['推荐模板', '历史模板']
const imagePrefix = import.meta.env.VITE_IMAGE_SUFFIX
const router = useRouter()
const route = useRoute()
const dataTotal = ref<number>(0)
const dataList = ref<Array<IPptApi.Response.TemplateResponse>>([])
const query = reactive<IPptApi.Request.TemplateRequest>({
  title: '',
  style: undefined,
  tone: undefined,
  scene: undefined,
  is_enable: 1,
  page: 1,
  limit: 20,
})
const sceneList = ref<Array<IPptApi.Response.TemplateCateResponse>>([])
const colorList = ref<Array<IPptApi.Response.TemplateCateResponse>>([])
const styleList = ref<Array<IPptApi.Response.TemplateCateResponse>>([])
const loading = ref<Boolean>(false)
const activeTab = ref<number>(0)
const selectedTemplate = ref<IPptApi.Response.TemplateResponse>({})
const selectedColor = ref<string>('')

const next = async () => {
  if (!selectedTemplate.value?.id) {
    return
  }
  if (parseInt(route.query.outline + '') === 1) {
    const lod = ElLoading.service({ fullscreen: true, text: 'ppt文件生成中，请稍后...' })
    const outline: string = window.sessionStorage.getItem(pptOutlineKey.value)
    if (!outline) {
      await router.replace({
        path: '/ai-ppt/generate-outline',
        query: {
          tid: selectedTemplate.value.id,
        },
      })
    }
    const outlineJson: PPTDataJson[] = markdownToJson(outline)
    const serverData: ServerData[] = markdownJsonToServer(outlineJson)
    const { id } = await httpOutlineToPptContent(serverData, selectedTemplate.value.id)
    lod.close()
    await router.replace({
      path: '/ai-ppt/generate-ppt',
      query: {
        id: id,
      },
    })
  } else {
    await router.replace({
      path: '/ai-ppt/generate-outline',
      query: {
        tid: selectedTemplate.value.id,
      },
    })
  }
}
const handleChangeTab = (index: number) => {
  if (activeTab.value === index) return
  activeTab.value = index
  getTemplateList()
}
const getDataList = async (category?: number) => {
  const res = await httpGetCategories({
    category,
    page: 1,
    limit: 999,
  })

  if (res && res.list.length) {
    let scene = []
    let color = []
    let style = []
    const resList = res.list
    resList.forEach((element) => {
      if (element.category === Scene.SCENE) {
        scene.push(element)
      } else if (element.category === Scene.COLOR) {
        color.push(element)
      } else if (element.category === Scene.STYLE) {
        style.push(element)
      }
    })
    styleList.value = [
      {
        id: 0,
        attribute: '全部风格',
      },
      ...style,
    ]
    colorList.value = [
      {
        id: 0,
        attribute: '#6789AB',
      },
      ...color,
    ]
    sceneList.value = [
      {
        id: 0,
        attribute: '全部场景',
      },
      ...scene,
    ]
  }
}

const getTemplateList = async () => {
  try {
    loading.value = true
    const response = await httpGetTemplates(
      query,
      activeTab.value === 0 ? 'show' : 'history',
    )
    if (!response) return
    const { list, total } = response
    dataList.value = list
    dataTotal.value = total
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}
/**
 * 筛选搜索
 */
const handleFilter = debounce(() => {
  query.page = 1
  getTemplateList()
}, 500)
/**
 * 选择模板
 * @param item
 */
const handleSelectTemplate = (item: IPptApi.Response.TemplateResponse) => {
  selectedTemplate.value = item
  let color = colorList.value.find((color) => color.id === item.tone)
  if (!color) return
  selectedColor.value = colorToRgba(color.attribute)
}
const headerHeight = ref(0)
const handleDomResize = (value) => {
  headerHeight.value = value.height
}
onBeforeMount(() => {
  getTemplateList()
  getDataList()
})
</script>
<style scoped lang="scss">
.template-list {
  margin-top: 10px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.6);
  box-shadow: var(--el-box-shadow);
  border-radius: 20px;
  padding: 10px 0;

  .template-area {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    display: flex;

    .tabs {
      padding: 10px 20px;
      width: 160px;
      height: 100%;
      border-right: 1px solid #ccc;

      .item-tab {
        font-size: 18px;
        padding: 6px;

        &:hover {
          cursor: pointer;
          color: var(--el-color-primary);
        }

        &.active {
          color: var(--el-color-primary);
          font-weight: 700;
        }
      }
    }

    .content {
      padding: 10px 20px;
      width: calc(100% - 160px);
      height: 100%;
      overflow: auto;
      @include scrollBar;

      .template-node {
        .node-item {
        }

        .node-img {
          cursor: pointer;

          &:hover {
            scale: 1.05;
            transition: all 0.1s;
          }
        }
      }
    }
  }
}
</style>
